package com.orangelife.mobile.confirmOrder.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.common.jump.CommonJumper;
import com.common.jump.PayJumper;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.address.activity.MakeAddressListActivity;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.common.jump.JumpManager;
import com.orangelife.mobile.confirmOrder.adapter.BusinessListViewAdapter;
import com.orangelife.mobile.confirmOrder.biz.GoodsHttpBiz;
import com.orangelife.mobile.confirmOrder.biz.MerchantOrderListHelper;
import com.orangelife.mobile.confirmOrder.biz.OrderBiz;
import com.orangelife.mobile.confirmOrder.biz.ConfirmOrderHttpBiz;
import com.orangelife.mobile.point.biz.MyPointBiz;
import com.orangelife.mobile.voucher.biz.VoucherHttpBiz;
import com.orangelife.mobile.confirmOrder.entity.MerchantInfo;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.voucher.biz.SelectedVoucherIDListHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品订单提交界面（涉及模块：周边商品、购物车）
 *
 * @author cfr, wgf
 */
public class ShoppingConfirmOrderActivity extends OrangeLifeBaseActivity
        implements OnClickListener {
    /**
     * 标题
     */
    private TextView tvTitle;
    /**
     * 总价
     */
    private TextView tvTotalPrice;
    /**
     * 抵用券
     */
    private TextView tvVoucher;
    private TextView tvVoucherVaule;
    /**
     * 总价
     */
    private TextView tvPayPrice;
    /**
     * 底部支付
     */
    private TextView tvPay;
    /**
     * 姓名
     */
    private TextView tvName;
    /**
     * 电话
     */
    private TextView tvPhone;
    /**
     * 地址
     */
    private TextView tvAddress;
    /**
     * 邮费
     */
    private TextView tvGoodsPostage;
    /**
     * 配送费
     */
    private TextView tvDeliverFee;
    /**
     * 应付总额
     */
    private TextView tvMeetMoney;
    private TextView tvPointTip;
    private String productID;
    private TextView tvPoint;//积分
    private TextView tvZeng;//积分
    private ImageView ivSwitch;//积分选择
    private ListView lvBussiness;
    private BusinessListViewAdapter businessListViewAdapter;
    /**
     * 从上个界面传过来的，产品规格列表，用来获取已选中的商品信息列表
     */
    private ArrayList<String> mLocalProductsList;
    /**
     * 购物车传过来的参数，本地商户商品列表
     */
    private List<HashMap<String, Object>> mLocalMerchantGoodList;
    private MerchantOrderListHelper merchant;
    private String isAccessToken = "";
    private String mOrderType = "";
    /**
     * 这个参数暂时没用
     */
    private String mGoodPrice = "";
    private String mTypeForPay = "";
    /**
     * WHAT-提交订单
     */
    private static final int WHAT_COMMIT_ORDER = 0;
    /**
     * WHAT-选中的商品列表
     */
    private static final int WHAT_SELECTED_GOOD_LIST = 3;

    public static final String SHOPPING_CART_LIST = "shoppingCart";
    public static final String GOODS_PRICES = "totalPrice";
    public static final String PRODUCT_IDS = "productIDs";
    public static final String PRODUCT_NUMBER = "orderNumber";
    public static final String PRODUCT_LIST_IDS = "productListIDs";
    public static final String SELLPLOY_ID = "sellPloyID";
    public static final String ORDER_TYPE = "orderType";
    public static final String MER_ID = "merID";
    public static final String TYPE = "type";
    private boolean isTehui = false;//是否是特惠跳转过来
    private int tehuiStatus = 0;//是否是特惠跳转过来
    private String activityGoodsID;
    private static final String IS_TEHUI = "isTehui";
    private boolean ivSwitchSelected = false;//是否使用积分抵扣
    private int isDeduction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_confirm_order);
        getIntentInfo();
        initView();
        requestSelectedMerchantGoodList();
    }

    private void getIntentInfo() {
        Intent it = getIntent();
        if (it == null) {
            return;
        }
        isTehui = it.getBooleanExtra(IS_TEHUI, false);
        if (isTehui) {
            activityGoodsID = it.getStringExtra("activityGoodsID");
            tehuiStatus = it.getIntExtra("tehuiStatus", 0);
        }
        mGoodPrice = it.getStringExtra(GOODS_PRICES);
        mOrderType = it.getStringExtra(ORDER_TYPE);
        mTypeForPay = getIntent().getExtras().getString(TYPE);
        mLocalProductsList = (ArrayList<String>) it.getSerializableExtra(PRODUCT_LIST_IDS);
        /*所有商品列表的形式都是 商户列表-商品列表（1个商户对应N个商品）*/
        mLocalMerchantGoodList = (List<HashMap<String, Object>>) it.getSerializableExtra(SHOPPING_CART_LIST);

    }


    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvPay = (TextView) findViewById(R.id.tvPay);
        tvZeng = (TextView) findViewById(R.id.tvZeng);
        tvPayPrice = (TextView) findViewById(R.id.tvPayPrice);
        tvPay.setOnClickListener(this);
        tvTitle.setText("确认订单");
        lvBussiness = (ListView) findViewById(R.id.lvBussiness);
        lvBussiness.addHeaderView(getAddressView());
        lvBussiness.addFooterView(getGoodInfoView());
    }

    /**
     * 价格计算板
     */
    private View getGoodInfoView() {
        View goodInfoView = this.getLayoutInflater().inflate(R.layout.include_goods_info, null);
        tvVoucherVaule = (TextView) goodInfoView.findViewById(R.id.tvVoucherVaule);
        tvTotalPrice = (TextView) goodInfoView.findViewById(R.id.tvAllPrice);
        tvGoodsPostage = (TextView) goodInfoView.findViewById(R.id.tvGoodsPostage);
        tvDeliverFee = (TextView) goodInfoView.findViewById(R.id.tvDeliverFee);
        tvMeetMoney = (TextView) goodInfoView.findViewById(R.id.tvMeetMoney);
        ivSwitch = (ImageView) goodInfoView.findViewById(R.id.ivSwitch);
        tvPoint = (TextView) goodInfoView.findViewById(R.id.tvPoint);
        ivSwitch.setOnClickListener(this);
        return goodInfoView;
    }

    /**
     * 收货地址界面
     */
    private View getAddressView() {
        View addressView = this.getLayoutInflater().inflate(R.layout.fragment_address, null);
        tvName = (TextView) addressView.findViewById(R.id.tv_username);
        tvPhone = (TextView) addressView.findViewById(R.id.tv_userphone);
        tvAddress = (TextView) addressView.findViewById(R.id.tv_address);
        return addressView;
    }

    /**
     * 已选中商品列表的适配器
     */
    private BusinessListViewAdapter getBusinessAdapter() {
        if (businessListViewAdapter == null) {
            businessListViewAdapter = new BusinessListViewAdapter(this);
            businessListViewAdapter.setMerchant(merchant);
            businessListViewAdapter.setTehuiStatus(tehuiStatus);
            businessListViewAdapter.setOnDispatchChangeListener(new BusinessListViewAdapter.OnDispatchChangeListener() {
                @Override
                public void onChange() {
                    updateAllTotalPriceAndView();
                }
            });
        } else {
            if (businessListViewAdapter.getMerchant() == null) {
                businessListViewAdapter.setMerchant(merchant);
                businessListViewAdapter.setTehuiStatus(tehuiStatus);
            }
        }
        return businessListViewAdapter;
    }

    /**
     * 请求已选择的商品列表
     */
    private void requestSelectedMerchantGoodList() {
        showDialog(this);
        GoodsHttpBiz.getSelectedMerchantGoodList(mLocalProductsList, handler, WHAT_SELECTED_GOOD_LIST);
    }

    /**
     * 处理-请求已选中的商户商品的列表-的响应数据
     */
    private void handleSelectedMerchantGoodList(String response) {
        closeDialog();
        Map<String, Object> map = JSONHelper.jsonToMap(
                response);
        if (map == null) {
            return;
        }
        //TODO 数据结构非常复杂，这里应该一开始就使用JavaBean来做，而不是List<Map>
        /*已选中的商品列表，格式为 ‘商户列表’ 嵌套 ‘商品列表’*/
        List<Map<String, Object>> selectedMerchantGoodList = (List<Map<String, Object>>) map.get("pageEntity");
        if (selectedMerchantGoodList != null && selectedMerchantGoodList.size() > 0) {
            initMerchantGoodListHelper(selectedMerchantGoodList);
            /*请求每个商户的最贵的抵用券的列表*/
//            if (tehuiStatus != 1) {//特惠中的商品无法使用抵用券
            requestVoucherHighestPriceList(merchant.getMerchantInfoList());
//            }
        }
        requestPoints();//请求可用积分
    }

    private void requestVoucherHighestPriceList(List<MerchantInfo> merchantInfoList) {
        VoucherHttpBiz.getVoucherHighestPriceListWithMerchant(merchantInfoList, VoucherHttpBiz.TYPE_GOOD, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                List<Map<String, Object>> highestPriceVoucherList = VoucherHttpBiz.handleVoucherHighestPriceList(response);
                if (highestPriceVoucherList != null) {
                    handleVoucherHighestPriceList(highestPriceVoucherList);
                }
            }
        });
    }

    /**
     * 根据商户id找到对应商户,设置该商户的最高金额抵用券
     */
    private void handleVoucherHighestPriceList(List<Map<String, Object>> highestPriceVoucherList) {
        merchant.addVoucherHighestPrice(highestPriceVoucherList);
        updateAllTotalPriceAndView();
        getBusinessAdapter().notifyDataSetChanged();
    }

    /**
     * 请求提交订单
     */
    private void requestCommitOrder() {
        showDialog(this);
        if (tehuiStatus == 1) {
            ConfirmOrderHttpBiz.commitOrder4Tehui(getOrderParamsMap(), handler, WHAT_COMMIT_ORDER);
        } else {
            ConfirmOrderHttpBiz.commitOrder(getOrderParamsMap(), handler, WHAT_COMMIT_ORDER);
        }
    }

    /**
     * 处理‘提交订单’的响应，即跳转到支付页
     */
    private void handleCommitOrder(String response) {
        Map<String, Object> jsonMap = JSONHelper.jsonToMap(
                response);
        if (jsonMap != null) {
            Map<String, Object> mapOrderDetail = (Map<String, Object>) jsonMap.get("entity");
            mapOrderDetail.put("productID", getIntent().getExtras().getString("productID"));
            jumpToPay(mapOrderDetail);
        }
    }

    //将选中的商品列表转为JavaBean
    private void initMerchantGoodListHelper(List<Map<String, Object>> selectedMerchantGoodList) {
        merchant = new MerchantOrderListHelper(selectedMerchantGoodList, mLocalMerchantGoodList);
        lvBussiness.setAdapter(getBusinessAdapter());
    }

    /**
     * 可能是跳转到支付界面
     */
    private void jumpToPay(Map<String, Object> mapOrderDetail) {
        PayJumper.jumpToPay(this, mapOrderDetail, mLocalProductsList, mTypeForPay, tvPhone.getText().toString());
        finish();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvPay:
                requestCommitOrder();
                break;
            case R.id.ivSwitch://是否使用积分抵扣
                showDialog(this);
                if (ivSwitchSelected) {
                    ivSwitchSelected = false;
                    isDeduction = 0;
                    ivSwitch.setSelected(ivSwitchSelected);
                    requestPoints();
                } else {
                    ivSwitchSelected = true;
                    isDeduction = 1;
                    ivSwitch.setSelected(ivSwitchSelected);
                    requestPoints();

                }
                break;
        }
    }

    /**
     * 提交订单时所需的参数
     */
    private Map<String, Object> getOrderParamsMap() {
        if (merchant == null) {
            return null;
        }
        List<MerchantInfo> merchantInfoList = merchant.getMerchantInfoList();
        Map<String, Object> orderParamMap = new HashMap<>();
        List<Map<String, Object>> listMerchants = new ArrayList<>();
        for (int i = 0; i < merchantInfoList.size(); i++) {
            MerchantInfo mi = merchantInfoList.get(i);
            ArrayList listGoods = new ArrayList<>();
            Map<String, Object> mapPaid = new HashMap<>();
            String dispatchID = mi.getDispatchID();
            if (StringUtil.isBlank(dispatchID)) {
                closeDialog();
                ToastHelper.getInstance()._toast("请先选择配送方式");
                return null;
            }
            mapPaid.put("dispatchID", dispatchID);
            mapPaid.put("merchantID", mi.getMerID());
            ArrayList<String> couponIDs = com.orangelife.mobile.voucher.biz.SelectedVoucherIDListHelper.getInstance().getSelfVoucherList();
            mapPaid.put("couponIDs", couponIDs);
            List<Map<String, Object>> goodList = mi.getGoodsList();
            for (int j = 0; j < goodList.size(); j++) {
                Map<String, String> mapGoods = new HashMap<>();
                mapGoods.put("productID", String.valueOf(goodList.get(j).get("productID")));
                mapGoods.put(PRODUCT_NUMBER, String.valueOf(goodList.get(j).get("orderNumber")));
                mapGoods.put("sellPloyID", mi.getSellployId());
                if (isTehui) {//特惠跳转过来时只要传activityGoodsID，不用传规格
                    mapGoods.put("activityGoodsID", activityGoodsID);
                }
                listGoods.add(mapGoods);
            }
            mapPaid.put("goods", listGoods);
            listMerchants.add(mapPaid);
        }
        orderParamMap.put("merchant", listMerchants);
        orderParamMap.put("shipPhone", tvPhone.getText().toString());
        orderParamMap.put("shipName", tvName.getText().toString());
        orderParamMap.put("shipAddr", tvAddress.getText().toString());
        orderParamMap.put("usePoints", isDeduction);//是否使用积分

        if (tehuiStatus != 1) {
            if (mOrderType != null) {
                orderParamMap.put("orderType", mOrderType);
            } else {
                orderParamMap.put("orderType", "14");
            }
        }
        return orderParamMap;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == JumpManager.RESULT_CODE_VOUCHER_LIST) {
            /*从抵用券列表跳回来*/
//            String totalSelectedVoucherPrice = data.getStringExtra(.TOTAL_COST);
            /*从那个商家跳回来的*/
//            String fromMerID = data.getStringExtra("merID");
//            String totalVoucherNum = data.getStringExtra("totalVoucherNum");
            merchant.updateMerchantVoucherInfo();
            updateAllTotalPriceAndView();
            businessListViewAdapter.notifyDataSetChanged();
        }
    }

    public void updateAllTotalPriceAndView() {
        OrderBiz.updateAllTotalPrice(merchant);
        setTextWithRmbFlag(tvGoodsPostage, merchant.totalPostogeFee);
        setTextWithRmbFlag(tvDeliverFee, merchant.totalDisptachFee);
        setTextWithRmbFlag(tvTotalPrice, merchant.totalGoodsPrice);
        setTextWithRmbFlag(tvVoucherVaule, merchant.totalVoucherPrice);
        setTextWithRmbFlag(tvMeetMoney, merchant.totalPrice);
        setTextWithRmbFlag(tvPayPrice, merchant.totalPrice);
    }

    private void setTextWithRmbFlag(TextView tv, String txt) {
        if (tv != null) {
            tv.setText(Constant.RMB_FLAG + String.valueOf(txt));
        }
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            DialogHelper.closeDialog(dialog);
            ExitApplication.getInstance().addPaidActivity(ShoppingConfirmOrderActivity.this);
            switch (msg.what) {
                case 1011:
                    isLogin(dialog);
                    break;
                case 500:
                    if (msg.obj.toString().equals("2")) {
                        ExitApplication.getInstance().addPaidActivity(ShoppingConfirmOrderActivity.this);
                    } else {
                        ToastHelper.getInstance()._toast(
                                msg.obj.toString());
                    }
                    break;
                case 1001:
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case WHAT_COMMIT_ORDER:/*提交订单*/
                    handleCommitOrder(String.valueOf(msg.obj));
                    break;
                case Constant.WHAT_PERSONAL_GOODS_LIMIT:
                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
                    break;
                case Constant.WHAT_ALL_GOODS_LIMIT:
                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
                    break;
                case 13:/*不知道*/
                    handleAccessToken(String.valueOf(msg.obj));
                    break;
                case WHAT_SELECTED_GOOD_LIST:/*选中商品列表*/
                    handleSelectedMerchantGoodList(String.valueOf(msg.obj));
                    break;
                case MyPointBiz.DEDUCTION:
                    handlePoints(String.valueOf(msg.obj));
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 不知道是什么东西
     */
    private void handleAccessToken(String response) {
        HashMap<String, Object> mapAccessToken = new HashMap<>();
        Map<String, Object> map = JSONHelper.jsonToMap(
                response);
        if (map == null) {
            return;
        }
        //TODO 这块注销和登录的操作，和抵用券完全无关，根本不该出现在这里
        mapAccessToken = (HashMap<String, Object>) map.get("entity");
        if ("true".equals(mapAccessToken.get("online"))) {
            isAccessToken = "true";
        } else {
            isAccessToken = "false";
        }
        if ("true".equals(isAccessToken)) {
            IntentHelper.getInstances().getIntent(ShoppingConfirmOrderActivity.this, MakeAddressListActivity.class);
        } else if ("false".equals(isAccessToken)) {
            ToastHelper.getInstance()._toast("请先登录");
            CommonJumper.jumpToLoginWhenExitWithClear(ShoppingConfirmOrderActivity.this);
        }
    }

    //获取积分
    private void requestPoints() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("isDeduction", isDeduction);
        List<Map<String, Object>> params = new ArrayList<>();
        for (int j = 0; j < merchant.getMerchantInfoList().size(); j++) {
            List<Map<String, Object>> goods = merchant.getMerchantInfoList().get(j).getGoodsList();
            for (int i = 0; i < goods.size(); i++) {
                Map<String, Object> product = new HashMap<>();
                product.put("payPrice", goods.get(i).get("price"));
                product.put("deduction", goods.get(i).get("deduction"));
                product.put("goodsNumber", goods.get(i).get("orderNumber"));
                params.add(product);
            }
        }
        map.put("pRuleID", merchant.getMerchantInfoList().get(0).getGoodsList().get(0).get("pRuleID").toString());
        map.put("params", params);
        MyPointBiz.getDeduction(map, handler);
    }

    /**
     * 处理积分规则的返回数据
     *
     * @param response
     */
    private void handlePoints(String response) {
        Map<String, Object> map = JSONHelper.jsonToMap(
                response);
        if (map == null) {
            return;
        }
        Map<String, Object> entity = (Map<String, Object>) map.get("entity");
        if (entity == null) {
            return;
        }
        //  deductionPoints	可抵用积分
        //  deductionPrice	可抵用多少钱
        //  points	抵用后可以得多少积分

        String deductionPrice = String.valueOf(entity.get("deductionPrice"));
        String deductionPoints = String.valueOf(entity.get("deductionPoints"));
        String points = String.valueOf(entity.get("points"));
        if (ivSwitchSelected) {
            merchant.deductionPrice = deductionPrice;
        } else {
            merchant.deductionPrice = "0";
        }
        tvPoint.setText("使用" + deductionPoints + "ml橙汁可抵扣" + deductionPrice + "金额");
        tvZeng.setText(points + "ml橙汁");
        updateAllTotalPriceAndView();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SelectedVoucherIDListHelper.getInstance().destroyBiz();
    }
}

